package cn.zhangxin.pethome.system.department.service.impl;

import cn.zhangxin.pethome.base.service.impl.BaseServiceImpl;
import cn.zhangxin.pethome.system.department.domain.Department;
import cn.zhangxin.pethome.system.department.mapper.DepartmentMapper;
import cn.zhangxin.pethome.system.department.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    @Transactional
    public void delete(Long id) {
        Long byParentId = departmentMapper.findByParentId(id);
        if (byParentId == 0) {
            departmentMapper.delete(id);
        }else {
            throw new RuntimeException("当前部门还有子部门，不能直接删除");
        }
    }

    @Override
    @Transactional
    public void update(Department department) {
        if(department.getId().equals(department.getParent_id())){
            throw new RuntimeException("不能设置为自己的子部门");
        }
        buildDirPath(department);
        departmentMapper.update(department);
    }

    @Override
    @Transactional
    public void add(Department department) {
        //先添加数据
        departmentMapper.add(department);
        buildDirPath(department);
        //修改数据
        departmentMapper.update(department);
    }

    //设置父路径 公共的代码
    private void buildDirPath(Department department){
        Long id = department.getId();
        if (department.getParent_id()==null){
            //拼接dirpath
            department.setDirPath("/"+id);
        }else {
            Department byParent1 = departmentMapper.findByParent(department.getParent_id());
            String dirPath = byParent1.getDirPath();
            department.setDirPath(dirPath+"/"+id);
        }
    }
    //无限级树
    //children 必须使用该名字 elementui要用
    @Override
    public List<Department> getTree() {

        //1.查询全部
        List<Department> deps = departmentMapper.findAll();

        //3.找儿子
        for (Department dep : deps){
            if(dep.getParent_id()!=null){
                for (Department parent : deps) {
                    if (dep.getParent_id() == parent.getId()){
                        parent.getChildren().add(dep);
                        break;
                    }
                }
            }
        }

        //2.找顶级
        List<Department> firstTree = deps.stream()
                //filter过滤器
                .filter(department -> department.getParent_id() == null)
                .collect(Collectors.toList());//转为list
        return firstTree;

    }


}
